import { Component, OnInit } from "@angular/core";
import { AxiosService } from "../../axios.service";
import * as FileSaver from "file-saver";
import * as moment from "moment";
import { Workbook } from "exceljs";

@Component({
  selector: "app-ruku-manage",
  templateUrl: "./ruku-manage.component.html",
  styleUrls: ["./ruku-manage.component.scss"],
})
export class RukuManageComponent implements OnInit {
  listOfData;
  uploadOk; // 入库成功的数据
  isShow = false; // 料號或廠商無法識別！
  documentName; // 获取的上传文件名
  docName; // 获取的上传文件信息({...})
  uploadData; // base64数据流
  downList: any[];
  exportlist: any;

  constructor(public axios: AxiosService) { }

  ngOnInit(): void {
    this.querydata();
  }

  // 获取上传文件的名称
  handleChange(info: any) {
    console.log(info);
    this.documentName = info.target.files[0]["name"]; // 获取上传文件的名称
    this.docName = info.target.files[0]; // 获取上传文件对象
    console.log(this.documentName);
    console.log(this.docName);
    const reader = new FileReader();
    reader.onload = () => {
      if (reader.result) {
        this.uploadData = reader.result;
        console.log(this.uploadData);
      }
    };
    reader.readAsDataURL(this.docName); // 将文件对象转为Base64格式
  }
  // 上传
  upLoad() {
    this.axios
      .axiosPost("Upload", {
        unionorder: "warehouse",
        workorder: "",
        filename: this.documentName,
        filedata: this.uploadData,
      })
      .then((data) => {
        if (data) {
          alert("已上傳");
          console.log(data);
          if (data["order"].length !== 0) {
            this.isShow = true;
            for (let i = 0; i < data["order"].length; i++) {
              console.log(data["order"][i].quatity);
              data["order"][i].quatity = Number(
                data["order"][i].quatity
              ).toFixed(3);
            }
            this.listOfData = data["order"];
            console.log(this.listOfData);
          }
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  // 获取入库成功的数据
  querydata() {
    // 备品信息
    let beipinMsg = [];
    // 厂商信息
    let changshangMsg = [];
    // 入庫成功的原始數據
    this.axios
      .axiosPost("QueryWarehouse", { offset: 0, count: 10000000 })
      .then((data) => {
        if (data) {
          this.uploadOk = data["order"];
          console.log(this.uploadOk);
          // 获取备品信息中的名称和单位
          this.axios.axiosPost("QueryBaseMaterial").then((data) => {
            if (data) {
              beipinMsg = data["order"];
              console.log(beipinMsg);
              // 获取厂商信息的税率
              this.axios.axiosPost("QueryFirmInfo").then((data) => {
                if (data) {
                  changshangMsg = data["order"];
                  console.log(changshangMsg);
                  for (let i = 0; i < this.uploadOk.length; i++) {
                    for (let j = 0; j < beipinMsg.length; j++) {
                      if (
                        this.uploadOk[i]["material_no"] ===
                        beipinMsg[j]["material_no"]
                      ) {
                        this.uploadOk[i].name = beipinMsg[j].name;
                        this.uploadOk[i].unit = beipinMsg[j].unit;
                      }
                    }
                    for (let a = 0; a < changshangMsg.length; a++) {
                      if (
                        this.uploadOk[i].manufacturer ===
                        changshangMsg[a].fullname
                      ) {
                        this.uploadOk[i].tax_rate = changshangMsg[a].tax_rate;
                      }
                    }
                    this.uploadOk[i].tax_price =
                      Number(this.uploadOk[i].price) /
                      (1 + Number(this.uploadOk[i].tax_rate));
                  }
                }
              });
            }
          });
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  // 下载入库成功的数据
  downLoad() {
    this.axios.axiosPost("AddDownloadCount")
      .then((data) => {
        console.log(data);
      })
      .catch((err) => {
        console.log(err);
      });
    let exportlist = [];
    console.log(this.uploadOk.length);
    if (this.uploadOk.length == 0) {
      alert("暫無數據");
    } else {
      for (let i = 0; i < this.uploadOk.length; i++) {
        exportlist.push({
          "PR NO": this.uploadOk[i].PR_NO,
          "PO NO": this.uploadOk[i].PO_NO,
          序號: this.uploadOk[i].SN,
          料號: this.uploadOk[i].material_no,
          數量: this.uploadOk[i].quatity,
          含稅單價: this.uploadOk[i].price,
          廠商: this.uploadOk[i].manufacturer,
          幣別: this.uploadOk[i].currency,
          卡口核放單號: this.uploadOk[i].check_no,
          名稱: this.uploadOk[i].name,
          單位: this.uploadOk[i].unit,
          稅率: this.uploadOk[i].tax_rate,
          入庫時間: this.uploadOk[i].timestamp,
          未稅單價: this.uploadOk[i].tax_price.toFixed(2),
          未稅總價: (this.uploadOk[i].tax_price.toFixed(2) * this.uploadOk[i].quatity).toFixed(2),
        });
      }
      console.log(exportlist);
      this.downList = [];
      exportlist.forEach((row: any) => {
        this.downList.push(Object.values(row))
      })
      let head = ["PR NO", "PO NO", "序號", "料號", "數量", "含稅單價", "廠商", "幣別", "卡口核放單號", "名稱", "單位", "稅率", "入庫時間", "未稅單價","未稅總價"]
      let reportData = {
        title: '入庫管理',
        headers: head,
        data: this.downList,
      };
      this.saveAsExcelFile(reportData);
    }
  }

  private saveAsExcelFile(excelData) {
    const title = excelData.title;
    const header = excelData.headers;
    const data = excelData.data;

    const workbook = new Workbook();
    const worksheet = workbook.addWorksheet("入庫管理");
    const headerRow = worksheet.addRow(header);
    const worksheet1 = workbook.getWorksheet(1);
    console.log(worksheet1);

    headerRow.eachCell((cell) => {
      cell.fill = {
        type: "pattern",
        pattern: "solid",
        // 设置表头背景颜色
        fgColor: { argb: "FFFFFF" },
      };
      cell.alignment = { vertical: "middle", horizontal: "center" };
      cell.font = {
        bold: true,
        // 设置表头的字体颜色
        color: { argb: "000000" },
        size: 12,
      };
      cell.border = {
        // 设置边框粗细
        top: { style: "thin" },
        left: { style: "thin" },
        bottom: { style: "thin" },
        right: { style: "thin" },
      };
    });
    // 设置表格内容居中对齐
    const contentarray = [];
    data.forEach((ele) => {
      contentarray.push(worksheet.addRow(ele));
    });
    // tslint:disable-next-line: prefer-for-of
    for (let i = 0; i < contentarray.length; i++) {
      contentarray[i].eachCell((cell) => {
        cell.border = {
          // 设置边框粗细
          top: { style: "thin" },
          left: { style: "thin" },
          bottom: { style: "thin" },
          right: { style: "thin" },
        };
        cell.fill = {
          type: "pattern",
          pattern: "solid",
          // 设置表头背景颜色
          fgColor: { argb: "FFFFFF" },
        };
        cell.alignment = { vertical: "middle", horizontal: "center" };
      });
    }

    worksheet.getColumn(1).width = 15;
    worksheet.getColumn(2).width = 15;
    worksheet.getColumn(3).width = 6;
    worksheet.getColumn(4).width = 16;
    worksheet.getColumn(5).width = 10;
    worksheet.getColumn(6).width = 10;
    worksheet.getColumn(7).width = 10;
    worksheet.getColumn(8).width = 6;
    worksheet.getColumn(9).width = 35;
    worksheet.getColumn(10).width = 45;
    worksheet.getColumn(11).width = 6;
    worksheet.getColumn(12).width = 6;
    worksheet.getColumn(13).width = 25;
    worksheet.getColumn(14).width = 10;
    worksheet.getColumn(15).width = 10;


    workbook.xlsx.writeBuffer().then((result) => {
      const blob = new Blob([result], {
        type:
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8",
      });
      FileSaver.saveAs(blob, title + "_" + moment().format("YYYYMMDDHHmmss") + ".xlsx");
    });
  }
}
